package org.my.spring.agent.app.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.my.spring.agent.common.domain.Result;
import org.my.spring.agent.mcp.core.config.AgentMcpConfig;
import org.my.spring.agent.mcp.core.domain.dto.IntentResult;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Objects;

/**
 * MCP工具调用服务
 * 负责与外部MCP工具进行通信，发送任务指令并获取执行结果
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AgentMcpService {
    private final WebClient.Builder webClientBuilder;

    /**
     * 调用MCP工具执行任务
     * @param mcpInfo MCP工具配置信息，包含工具名称、启用状态和URL
     * @param intentResult 意图识别结果，包含任务类型和执行步骤
     * @return 工具执行结果字符串，如果执行失败则返回空字符串
     */
    public String callTool(AgentMcpConfig.McpInfo mcpInfo, IntentResult intentResult) {
        log.info("callTool: {} intentResult: {}", mcpInfo, intentResult);
        // 使用 WebClient 发送 SSE 请求
        WebClient webClient = webClientBuilder.build();
        Result<?> result = webClient.post()
                .uri(mcpInfo.url())
                .bodyValue(intentResult)
                .retrieve()
                .bodyToMono(Result.class)
                .block();
        log.info("callTool result: {}", result);
        if (Result.isError(result)) {
            return "";
        }
        return Objects.toString(result.message(), "");
    }
}
